package com.zysdev.videochart

import android.media.MediaCodec
import android.media.MediaFormat
import android.util.Log
import android.view.Surface
import java.io.IOException

class DecodecPlayerLiveH265 {
    private val TAG = "---"
    private var mediaCodec: MediaCodec? = null

    fun initDecode(surface: Surface) {
        try {
            mediaCodec = MediaCodec.createDecoderByType("video/hevc")
            val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, 1080, 1920)
            format.setInteger(MediaFormat.KEY_BIT_RATE, 1080 * 1920)
            format.setInteger(MediaFormat.KEY_FRAME_RATE, 15)
            format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 5)
            mediaCodec!!.configure(
                format,
                surface,
                null, 0
            )
            mediaCodec!!.start()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun callBack(data: ByteArray?) {
        if (data?.isEmpty() == true) {
            Log.e("---","---callBack--data.isEmpty()")
            return
        }
        Log.i(TAG, "接收到消息: " + data!!.size)
        val index = mediaCodec!!.dequeueInputBuffer(100000)
        if (index >= 0) {
            val inputBuffer = mediaCodec!!.getInputBuffer(index)
            inputBuffer!!.clear()
            inputBuffer.put(data, 0, data.size)
            //dsp芯片解码    解码 的 传进去的   只需要保证编码顺序就好了  1000
            mediaCodec!!.queueInputBuffer(
                index,
                0, data.size, System.currentTimeMillis(), 0
            )
        }
        //        获取到解码后的数据  编码 ipbn
        val bufferInfo = MediaCodec.BufferInfo()
        var outputBufferIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 100000)
        while (outputBufferIndex >= 0) {
            mediaCodec!!.releaseOutputBuffer(outputBufferIndex, true)
            outputBufferIndex = mediaCodec!!.dequeueOutputBuffer(bufferInfo, 0)
        }
    }
}